import React, { useEffect, useState, useRef } from "react";
import { Button, Table, Switch, Modal } from "antd";
import axios from "axios";
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined
} from "@ant-design/icons";
import UserForm from "../../../components/user-manage/UserForm";
const { confirm } = Modal;

export default function UserList() {
  const [dataSource, setdataSource] = useState([]);
  const [addMoadlVisible, setaddMoadlVisible] = useState(false);
  const [updateMoadlVisible, setupdateMoadlVisible] = useState(false);
  const [regions, setregions] = useState([]);
  const [roles, setroles] = useState([]);
  const addFormRef = useRef(null);
  const updateFormRef = useRef(null);
  const [currentId, setcurrentId] = useState(null);
  const [regionEnable, setregionEnable] = useState(false);
  useEffect(() => {
    axios.get("/users?_expand=role").then(({ data }) => {
      let list = [];
      const { id, roleId, region } = JSON.parse(localStorage.getItem("token"));
      const roleObj = {
        1: "superAdmin",
        2: "admin",
        3: "editer"
      };
      if (roleObj[roleId] === "superAdmin") {
        // 超级管理员返回所有用户
        list = data;
      } else if (roleObj[roleId] === "admin") {
        // 区域管理员返回自己和区域编辑用户
        list = [
          ...data.filter(v => v.id === id),
          ...data.filter(
            v => v.region === region && roleObj[v.roleId] === "editer"
          )
        ];
      }
      setdataSource(list);
    });
    axios.get("/regions").then(({ data }) => {
      setregions(data);
    });
    axios.get("/roles").then(({ data }) => {
      setroles(data);
    });
  }, []);
  const columns = [
    {
      title: "区域",
      dataIndex: "region",
      filters: [
        { text: "全球", value: "" },
        ...regions.map(v => ({
          text: v.title,
          value: v.value
        }))
      ],
      onFilter: (value, record) => {
        if (value === "全球") return record.region === "";
        return record.region === value;
      },
      render(region) {
        return region === "" ? "全球" : region;
      }
    },
    {
      title: "角色名称",
      dataIndex: "role",
      render(role) {
        return role?.roleName;
      }
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "address"
    },
    {
      title: "用户状态",
      render(row) {
        return (
          <Switch
            checked={row.roleState}
            disabled={row.id === 1}
            onChange={() => {
              roleStateChange(row);
            }}
          ></Switch>
        );
      }
    },
    {
      title: "操作",
      render(item) {
        return (
          <div>
            <Button
              danger
              icon={<DeleteOutlined />}
              shape="circle"
              size="large"
              style={{ marginRight: "10px" }}
              disabled={item.id === 1}
              onClick={() => showDelConfirm(item)}
            />
            <Button
              type="primary"
              icon={<EditOutlined />}
              shape="circle"
              size="large"
              disabled={item.id === 1}
              onClick={() => {
                setcurrentId(item.id);
                setTimeout(() => {
                  setupdateMoadlVisible(true);
                  setregionEnable(item.roleId === 1);
                  updateFormRef.current.setFieldsValue(item);
                }, 0);
              }}
            />
          </div>
        );
      }
    }
  ];
  const roleStateChange = item => {
    setdataSource(
      dataSource.map(v => {
        if (v.id === item.id) v.roleState = !v.roleState;
        return v;
      })
    );
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState
    });
  };
  function showDelConfirm(item) {
    confirm({
      title: "您确定删除该用户吗?",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        setdataSource(dataSource.filter(v => v.id !== item.id));
        axios.delete(`/users/${item.id}`);
      },
      onCancel() {}
    });
  }
  const onAddOk = () => {
    addFormRef.current.validateFields().then(values => {
      setaddMoadlVisible(false);
      addFormRef.current.resetFields();
      axios
        .post("/users", {
          roleState: true,
          default: true,
          ...values
        })
        .then(({ data }) => {
          setdataSource([
            ...dataSource,
            {
              ...data,
              role: roles.find(v => v.id === values.roleId)
            }
          ]);
        });
    });
  };
  const onUpdateOk = () => {
    updateFormRef.current.validateFields().then(values => {
      setupdateMoadlVisible(false);
      updateFormRef.current.resetFields();
      setdataSource(
        dataSource.map(v => {
          if (v.id === currentId) {
            return {
              ...v,
              ...values,
              role: roles.find(k => k.id === values.roleId)
            };
          }
          return v;
        })
      );
      axios.patch(`/users/${currentId}`, values);
    });
  };
  return (
    <div>
      <Button type="primary" onClick={() => setaddMoadlVisible(true)}>
        添加用户
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={item => item.id}
        pagination={{ pageSize: 5 }}
      />
      <Modal
        visible={addMoadlVisible}
        title="添加用户"
        okText="添加"
        cancelText="取消"
        onCancel={() => {
          setaddMoadlVisible(false);
        }}
        onOk={onAddOk}
      >
        <UserForm ref={addFormRef} regions={regions} roles={roles} />
      </Modal>
      <Modal
        visible={updateMoadlVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setupdateMoadlVisible(false);
          setregionEnable(!regionEnable);
        }}
        onOk={onUpdateOk}
      >
        <UserForm
          ref={updateFormRef}
          regions={regions}
          roles={roles}
          regionEnable={regionEnable}
          type="edit"
        />
      </Modal>
    </div>
  );
}
